package com.zz.furn.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zz.furn.bean.Furn;
import com.zz.furn.service.FurnService;
import com.zz.furn.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/furn")
public class FurnController{
    @Autowired
    private FurnService furnService;

    @PostMapping("/save")
    public Result<Furn> save(@Validated @RequestBody Furn furn, Errors errors){
        Map<String, Object> map = new HashMap<>();
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError e : fieldErrors) {
            map.put(e.getField(), e.getDefaultMessage());
        }
        if(map.isEmpty()){
            boolean save = furnService.save(furn);
            if(save){
                return Result.success();
            }else {
                return Result.error("500", "保存失败");
            }
        }else{
            return Result.error("505", "后端校验失败", map);
        }

    }

    @GetMapping("/list")
    public Result<List<Furn>> list(){
        List<Furn> list = furnService.list();
        return Result.success(list);
    }

    @GetMapping("/listPage")
    public Result<Page> listPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "5") Integer pageSize){
        Page<Furn> page = furnService.page(new Page<>(pageNum, pageSize));
        return Result.success(page);
    }

    @GetMapping("/listSearch")
    public Result<Page> listSearch(@RequestParam(defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "5") Integer pageSize,
                                   @RequestParam(defaultValue = "") String search){
        /*QueryWrapper<Furn> qw = new QueryWrapper<>();
        if(StringUtils.hasText(search)){
            qw.like("name", search);
        }*/
        LambdaQueryWrapper<Furn> qw = new LambdaQueryWrapper<>();
        if(StringUtils.hasText(search)){
            qw.like(Furn::getName, search);
        }
        Page<Furn> page = furnService.page(new Page<>(pageNum, pageSize), qw);
        return Result.success(page);
    }

    @PutMapping("/edit")
    public Result edit(@RequestBody Furn furn){
        return Result.success(furnService.updateById(furn));
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id){
        return Result.success(furnService.removeById(id));
    }
}
